import { useState } from 'react'
import { View, Image, Text } from '@tarojs/components'
import Taro, { useDidShow } from '@tarojs/taro'
import { Footer } from '@/components/index'
import logo from '@/img/login/logo.svg'
import account from '@/img/login/account.svg'
import passwordIcon from '@/img/login/password.svg'
import codeIcon from '@/img/login/code.svg'
import btnIcon from '@/img/login/login_btn.svg'
import loginBk from '@/img/login/login_bk.svg'
import { Input } from '@nutui/nutui-react-taro'
import { userLogin, getCaptcha } from '@/axios/user'
import './index.scss'

const LoginIndex: React.FC = () => {
  const [captchaUrl, setCapthcaUrl] = useState<string>('')
  const [formData, setFormData] = useState<any>({})
  const userInfo = Taro.getStorageSync('USERINFO') || {}
  useDidShow(() => {
    Taro.hideHomeButton()

    if (userInfo && userInfo.token) {
      if (userInfo.userRoleCode == 2) {
        // 班级账号
        Taro.switchTab({
          url: '/pages/classMgt/index'
        })
      } else if (userInfo.userRoleCode == 3) {
        Taro.switchTab({
          url: '/pages/schoolMgt/index'
        })
      } else if (userInfo.userRoleCode == 1) {
        Taro.redirectTo({
          url: '/subPackages/pages/user/index'
        })
      }
    } else {
      getCaptchaImg()
    }
  })

  const handleClickSave = async () => {
    try {
      const params = {
        ...formData
      }
      if (!params.account) {
        Taro.showToast({
          icon: 'none',
          title: '请输入账号!'
        })
        return
      }
      if (!params.password) {
        Taro.showToast({
          icon: 'none',
          title: '请输入密码!'
        })
        return
      }
      if (!params.capture) {
        Taro.showToast({
          icon: 'none',
          title: '请输入图片验证码!'
        })
        return
      }

      const Cookie = Taro.getStorageSync('cookies')
      const results = await userLogin(params, {
        header: { Cookie: Cookie }
      })
      // 设置token
      Taro.setStorageSync('TOKEN', results?.token)
      //设置用户信息
      Taro.setStorageSync('USERINFO', results)
      // 根据 用户 角色 跳转  学生跳转 测评页面  教师跳转 班级管理  学校跳转 学校管理
      Taro.showToast({
        icon: 'success',
        title: '登录成功!',
        complete: () => {
          setTimeout(() => {
            if (results.userRoleCode == 2) {
              // 班级账号
              Taro.switchTab({
                url: '/pages/classMgt/index'
              })
            } else if (results.userRoleCode == 3) {
              Taro.switchTab({
                url: '/pages/schoolMgt/index'
              })
            } else if (results.userRoleCode == 1) {
              Taro.redirectTo({
                url: '/subPackages/pages/user/index'
              })
            }
          }, 1500)
        }
      })
    } catch {}
  }

  const getCaptchaImg = async () => {
    try {
      const results = await getCaptcha()
      const imgUrl =
        'data:image/png;base64,' + Taro.arrayBufferToBase64(results)
      setCapthcaUrl(imgUrl)
    } catch {}
  }

  const handleChangeForm = (field: string, value: any) => {
    setFormData({ ...formData, [field]: value })
  }

  const onOpenForgot = () => {
    Taro.navigateTo({
      url: '/subPackages/pages/forgot/index'
    })
  }

  const onOpenRegister = () => {
    Taro.navigateTo({
      url: '/subPackages/pages/register/index'
    })
  }

  return (
    <View className='login_page flex_column'>
      <View className='login_box flex_column'>
        <View className='flex_row login_row'>
          <Image src={logo} className='logo_img' />
          <Text className='logo_line'></Text>
          <Text className='logo_text'>育新创联生涯教育平台</Text>
        </View>

        <Image src={loginBk} className='bk_img' />
        <View className='form_box flex_column'>
          <View className='form_item flex_row'>
            <Image src={account} className='form_icon' />
            <Input
              placeholder='请输入账号'
              value={formData.account}
              onChange={handleChangeForm.bind(this, 'account')}
              className='form_input'
            />
          </View>
          <View className='form_item flex_row'>
            <Image src={passwordIcon} className='form_icon' />
            <Input
              placeholder='请输入密码'
              type='password'
              value={formData.password}
              onChange={handleChangeForm.bind(this, 'password')}
              className='form_input'
            />
          </View>
          <View className='form_code_box flex_row'>
            <View className='form_item flex_row form_code_input'>
              <Image src={codeIcon} className='form_icon' />
              <Input
                placeholder='请输入验证码'
                value={formData.capture}
                onChange={handleChangeForm.bind(this, 'capture')}
                className='form_input'
              />
            </View>
            <View className='form_code' onClick={getCaptchaImg}>
              <Image src={captchaUrl} />
            </View>
          </View>
        </View>
        <View className='forgot'>
          <Text onClick={onOpenForgot}>忘记密码？</Text>
        </View>
        <View className='login_btn' onClick={handleClickSave}>
          <Image src={btnIcon} />
        </View>
        <Text className='register' onClick={onOpenRegister}>
          新用户注册
        </Text>
      </View>
      <Footer />
    </View>
  )
}

export default LoginIndex
